package sardine;

import sardine.function.Route;
import sardine.utils.Asserts;

/**
 * @auth bruce-sha
 * @date 2015/5/21
 */
public abstract class SimpleRoute<T> implements Route<T> {

    private final String path;
    private final String acceptType;

    protected SimpleRoute(final String path) {
        this(path, SardineBase.DEFAULT_ACCEPT_TYPE);
    }

    protected SimpleRoute(final String path, final String acceptType) {
        this.path = Asserts.notNull(path);
        this.acceptType = Asserts.notNull(acceptType);
    }

    public String getAcceptType() {
        return acceptType;
    }

    public String getPath() {
        return this.path;
    }

    public abstract T apply(Request request, Response response) throws Exception;

    /**
     * This method should render the given element into something that can be send through Response element.
     * By default this method returns the result of calling toString method in given element, but can be overridden.
     *
     * @param element to be rendered.
     * @return body content.
     * @throws Exception when render fails
     */
    //TODO change String return type to Stream. It should be done in another issue.
    public String render(T element) throws Exception {
        //optional??
        if (element != null) {
            return element.toString();
        } else {
            return null;
        }
    }
}